//
//  QHTOrderButton.m
//  B2CStore
//
//  Created by 陶磊 on 2020/2/11.
//  Copyright © 2020 QHT. All rights reserved.
//

#import "QHTOrderButton.h"

@implementation QHTOrderButton

- (void)handleControlEvent:(UIControlEvents)event
                 withBlock:(CLCWActionBlock) action
{
    _actionBlock = action;
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
    
}

- (void)callActionBlock:(id)sender{
    _actionBlock();
}

-(instancetype)init{
    self = [super init];
    if (self) {

//        [self bringSubviewToFront:_badgeLab];
    }
    return self;
}
-(void)setFrame:(CGRect)frame{
        [super setFrame:frame];
        [self setSubFrame];
    
            _badgeLab = [[UILabel alloc] init];
            _badgeLab.backgroundColor = [UIColor whiteColor];
            _badgeLab.layer.borderWidth = 1;
            _badgeLab.layer.borderColor = [UIColor base_blue].CGColor;
            _badgeLab.font = [UIFont systemFontOfSize:10];
            _badgeLab.textColor = [UIColor base_blue];
            _badgeLab.clipsToBounds = YES;
            _badgeLab.textAlignment = NSTextAlignmentCenter;
            [self addSubview:_badgeLab];
    
}

-(void)setIsRedBall:(BOOL)isRedBall{
    _isRedBall = isRedBall;
    [self setSubFrame];
}

-(void)setSubFrame{
    
    CGFloat badgeH;
    CGFloat badgeW;
    
    [self showText];
    
    if (_isRedBall) {
        badgeH = 8;
        badgeW = 8;
    }else{
        badgeH = 15;
        badgeW = [_badgeLab sizeThatFits:CGSizeMake(MAXFLOAT, badgeH)].width + 5;
        if (badgeW > 40) {
            badgeW = 40;
        }
        if (badgeW < badgeH) {
            badgeW = badgeH;
        }


    }
    
    
    _badgeLab.frame = CGRectMake(0, 0, badgeW, badgeH);
    _badgeLab.layer.cornerRadius = badgeH / 2;
    
    if (self.imageView.image) {
        CGPoint center = CGPointMake(CGRectGetMaxX(self.imageView.frame), self.imageView.frame.origin.y);
        _badgeLab.center = center;
    }else{
        CGPoint center = CGPointMake(self.bounds.size.width - 22, self.bounds.origin.y + 22);
        _badgeLab.center = center;
    }

}

-(void)setBadgeValue:(NSInteger)badgeValue{
    _badgeValue = badgeValue;
    [self setSubFrame];
}

-(void)showText{
    if (_badgeValue <= 0) {
        _badgeLab.hidden = YES;
    }else
        _badgeLab.hidden = NO;
        
    if (_isRedBall) {
        _badgeLab.text = @"";
    } else{
        if (_badgeValue > 99) {
            _badgeLab.text = @"99+";
        }else
            _badgeLab.text = [NSString stringWithFormat:@"%ld",(long)_badgeValue];
    }
}
@end
